package com.exam.api.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.exam.api.common.*;
import com.exam.api.dto.ExamDetailDTO;
import com.exam.api.dto.ExamStudentDTO;
import com.exam.api.service.ExamDetailService;
import com.exam.api.service.ExamStudentService;
import com.exam.api.vo.ExcelListener;
import com.exam.api.vo.ExcelQuestionVO;
import com.exam.api.vo.StuQuestionVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.DecimalFormat;
import java.util.*;

import com.exam.api.service.ExamService;
import com.exam.api.dto.ExamDTO;
import com.exam.api.service.StudentService;
import com.exam.api.dto.StudentDTO;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;

import com.exam.api.common.BaseSelectEntity;
import cn.hutool.core.collection.CollectionUtil;

/**
 * @description: 学生考试管理对外接口层
 * @author: wuming
 * @create: 2024.05.03 13:24:03
 */
@RestController
@RequestMapping("/examStudent")
public class ExamStudentController extends BaseController<ExamStudentService, ExamStudentDTO> {

    @Autowired
    private ExamService examService;
    @Autowired
    private StudentService studentService;

    @Autowired
    private ExamDetailService examDetailService;

    @Override
    @Resource(name = "examStudentService")
    protected void setBaseService(ExamStudentService examStudentService) {
        this.baseService = examStudentService;
    }

    /**
     * 默认分页查询
     *
     * @param examStudentDTO
     * @return
     */
    @PostMapping("/page")
    public ReturnMsg page(@RequestBody ExamStudentDTO examStudentDTO) {
        Page<ExamStudentDTO> studentDTOPage = baseService.basePage(examStudentDTO);
        List<ExamStudentDTO> studentDTOPageRecords = studentDTOPage.getRecords();
        if (CollectionUtil.isNotEmpty(studentDTOPageRecords)) {
            for (ExamStudentDTO studentDTO : studentDTOPageRecords) {
                ExamDetailDTO examDetailDTO = new ExamDetailDTO();
                examDetailDTO.setExamId(studentDTO.getExamId());
                examDetailDTO.setStudentId(studentDTO.getStudentId());
                List<ExamDetailDTO> list = examDetailService.findList(examDetailDTO);
                studentDTO.setExamDetailDTOS(list);
            }
        }
        return ReturnMsg.ok(studentDTOPage);
    }

    /**
     * 根据XML中的sql语句进行查询
     *
     * @param examStudentDTO
     * @return
     */
    @PostMapping(value = "/findList")
    public ReturnMsg findList(@RequestBody ExamStudentDTO examStudentDTO) {
        List<ExamStudentDTO> baseServiceList = baseService.findList(examStudentDTO);
        if (CollectionUtil.isNotEmpty(baseServiceList)) {
            for (ExamStudentDTO studentDTO : baseServiceList) {
                ExamDetailDTO examDetailDTO = new ExamDetailDTO();
                examDetailDTO.setExamId(studentDTO.getExamId());
                examDetailDTO.setStudentId(studentDTO.getStudentId());
                List<ExamDetailDTO> list = examDetailService.findList(examDetailDTO);
                studentDTO.setExamDetailDTOS(list);
            }
        }
        return ReturnMsg.ok(baseServiceList);
    }

    @Override
    protected void beforeSave(ExamStudentDTO entity) throws Exception {
        entity.setCreateTime(new Date());
        entity.setEndTime(examService.getById(entity.getExamId()).getEndTime());
        Long studentId = entity.getStudentId();
        Long examId = entity.getExamId();
        ExamStudentDTO examStudentDTO = new ExamStudentDTO();
        examStudentDTO.setExamId(examId);
        examStudentDTO.setStudentId(studentId);
        List<ExamStudentDTO> baseServiceList = this.baseService.findList(examStudentDTO);
        if (CollectionUtil.isNotEmpty(baseServiceList)) throw new Exception("当前学生已经存在于该考试中");
        super.beforeSave(entity);
    }

    @Value("${new-tomcat.folder}")
    private String newTomcatFolder;


    @PostMapping("/saveData")
    public ReturnMsg saveData(@RequestBody ExamDetailDTO examDetailDTO) throws Exception {
        // 先删除之前的
        File file = new File(newTomcatFolder + examDetailDTO.getUrl());
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        List<ExcelQuestionVO> list = EasyExcel.read(inputStream).head(ExcelQuestionVO.class).sheet().doReadSync();
        if (CollectionUtil.isEmpty(list)) throw new Exception("excel格式有误");
        Collections.shuffle(list);
        ExcelQuestionVO excelQuestionVO = list.get(0);
        if (excelQuestionVO.getYuwen() == null || excelQuestionVO.getShuxue() == null || excelQuestionVO.getYingyu() == null) {
            throw new Exception("excel格式有误");
        }
        if (excelQuestionVO.getTotal() == null) {
            return ReturnMsg.error("学生：" + excelQuestionVO.getName() + "总分未计算,本次测试分数为0分");
        }
        if (excelQuestionVO.getAvg() == null) {
            return ReturnMsg.error("学生：" + excelQuestionVO.getName() + "平均分未计算,本次测试分数为0分");
        }
        Long total = excelQuestionVO.getYuwen() + excelQuestionVO.getShuxue() + excelQuestionVO.getYingyu();
        if (!total.equals(excelQuestionVO.getTotal())) {
            return ReturnMsg.error("学生：" + excelQuestionVO.getName() + "总分计算不正确，正确总分应为" + total + ",本次测试分数为0分");
        }
        double average = total / 3;
        DecimalFormat df = new DecimalFormat("#.00");
        String formattedAverage = df.format(average);
        double avg = excelQuestionVO.getAvg();
        String avg1 = df.format(avg);
        if (!formattedAverage.equals(avg1)) {
            return ReturnMsg.error("学生：" + excelQuestionVO.getName() + "平均分计算不正确，正确平均分应为" + formattedAverage + ",本次测试分数为0分");
        }
        return ReturnMsg.ok("本次测试通过,满分！");
    }


    @GetMapping("/all/exam")
    public ReturnMsg allExam(@RequestParam(required = false) Long teacherId) {
        List<BaseSelectEntity> list = new ArrayList<>();
        LambdaQueryWrapper<ExamDTO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (teacherId != null) {
            lambdaQueryWrapper.eq(ExamDTO::getTeacherId, teacherId);
        }
        List<ExamDTO> dtos = examService.list(lambdaQueryWrapper);
        for (ExamDTO dto : dtos) {
            BaseSelectEntity baseSelectEntity = new BaseSelectEntity();
            baseSelectEntity.setKey(dto.getId());
            baseSelectEntity.setValue(dto.getExamName());
            list.add(baseSelectEntity);
        }
        return ReturnMsg.ok(list);
    }

    @GetMapping("/all/student")
    public ReturnMsg allStudent() {
        List<BaseSelectEntity> list = new ArrayList<>();
        List<StudentDTO> dtos = studentService.list();
        for (StudentDTO dto : dtos) {
            BaseSelectEntity baseSelectEntity = new BaseSelectEntity();
            baseSelectEntity.setKey(dto.getId());
            baseSelectEntity.setValue(dto.getName());
            list.add(baseSelectEntity);
        }
        return ReturnMsg.ok(list);
    }

}

